import exceptions
import logging
import traceback

from django.core.exceptions import PermissionDenied
from django.shortcuts import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.generic.base import View

import helpers
import models
from django.conf import settings

logger = logging.getLogger("main")

class ApiView(View):
    @csrf_exempt
    def dispatch(self, *args, **kwargs):
        return super(ApiView, self).dispatch(*args, **kwargs)

    def get(self, request, *args, **kwargs):
        self.api_reply = helpers.ApiJsonReply()
        name = self.__class__.__name__
        logger.info('get begin: %s', name)
        try:
            logger.info(u'%s: req: %s, client: %s', name, request.GET, self.get_client_ip())
            self.api_reply = self.get_valid(request.GET)
        except exceptions.ApiError as e:
            self.api_reply.set_error(e)
            logger.error(u'%s: resp: %s error: %s', self.__class__.__name__, self.api_reply, str(e))
        except:
            # send email
            debug = traceback.format_exc()
            logger.error(debug)
            self.api_reply.set_error(exceptions.ApiUnexpectedError(debug='internal error'))
        logger.info('get end: %s', name)

        response = HttpResponse(
            unicode(self.api_reply),
            content_type='application/json')

        return response

    def post(self, request, *args, **kwargs):
        name = self.__class__.__name__
        logger.info('post begin: %s', name)
        self.api_reply = self.reply_class()

        try:
            api_request = self.request_class(request)
            logger.info(u'%s: req: %s, client: %s', name, api_request.cleaned_data, self.get_client_ip())
            self.api_reply = self.post_valid(api_request)
        except exceptions.ApiError as e:
            self.api_reply.set_error(e)
            logger.error(u'%s: resp: %s error: %s', self.__class__.__name__, self.api_reply, str(e))
        except:
            # send email
            debug = traceback.format_exc()
            logger.error(debug)
            self.api_reply.set_error(exceptions.ApiUnexpectedError(debug='internal error'))
        logger.info('post end: %s', name)

        response = HttpResponse(
            unicode(self.api_reply),
            content_type='application/json')

        return response

    def get_client_ip(self):
        x_forwarded_for = self.request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = self.request.META.get('REMOTE_ADDR')
        return ip

class StaffView(ApiView):
    def post_valid(self, api_request):
        session = api_request.request.session

        if not settings.DEVELOPMENT and not api_request.request.user.is_authenticated():
            logger.error("login required. %s", self.request.body)
            raise exceptions.ApiLoginRequiredError('login required')

        if settings.DEVELOPMENT:
            email = 'zdjx@91fengchao.com'
        else:
            email = api_request.request.user.email

        return self.staff_valid(email, api_request)

    def get_valid(self, api_request):
        email = 'zdjx@91fengchao.com'
        return self.staff_valid(email, api_request)
